package com._5704.website.util;

import com._5704.website.entity.ToEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 发送邮件的工具
 */
@Component
public class EmailUtil {

    private static JavaMailSenderImpl mailSender;
    private static String sender;

    @Autowired
    private  void setMailSender(JavaMailSenderImpl mailSenderIn) {
        mailSender = mailSenderIn;
    }

    @Value("${spring.mail.username}")
    private void setSender(String senderIn){
        sender = senderIn;
    }

    /**
     * 发送邮件
     * @param toEmail 自定义的邮件实体
     */
    public static void send(ToEmail toEmail){
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper minehelper = new MimeMessageHelper(message, true);
            // 邮箱设置
            minehelper.setTo(toEmail.getUser());
            minehelper.setSubject(toEmail.getSubject());
            minehelper.setText(toEmail.getContent(),true);
            minehelper.setFrom(sender);
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }


    }
}
